<?php
	
	//change nominate my blog widget code to use different button image
	$blogurl = "";
	if(isset($_GET['getwidgetcode'])) {
		if($_GET['getwidgetcode']=='black') {
			$blackstyle = "class='pickhiglight'";
			$whitestyle = "";
		} else {
			$whitestyle = "class='pickhiglight'";
			$blackstyle = "";
		}
		$burl = rtrim(HTTP_SERVER,'/')."?getwidgetcode=";
		$blogurl = "<span ".$whitestyle." style='float:left;'><a href='".$burl."white' onclick=\"new Ajax.Updater('yourwidget', '".$burl."white');\" title='white background widget'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-white.gif' alt='nominate this blog' /></a></span> ";
		$blogurl .= "<span ".$blackstyle." style='float:left;'><a href='".$burl."black' onclick=\"new Ajax.Updater('yourwidget', '".$burl."black');\" title='black background widget'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-black.gif' alt='nominate this blog' /></a></span><div style='clear:both;'></div>";
		$widgetcode = "<a href='".HTTP_SERVER."nominate?blog=".urlencode($_SESSION['widget-blogurl'])."&category=".$_SESSION['widget-categories']."' title='Nominate Me for the 2007 SA Blog Awards'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-".(($blackstyle!="")?"black":"white").".gif' alt='nominate this blog' /></a>";
		$blogurl = "<div id='get-widget-code'>".$blogurl."<small>Select the badge you like above and then <br />copy and paste this code below into your blog</small><br /><textarea name='copycode' rows='3' cols='30' onclick='this.select();'>".$widgetcode."</textarea></div>";
		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $blogurl;
			exit;
		}
	}
	//get nominate my blog widget
	if(isset($_POST['blogurl'])) {
		$_SESSION['widget-categories'] = implode(",", $_POST['blogcategory']);
		$_SESSION['widget-blogurl'] = $_POST['blogurl'];
		if(valid_url($_POST['blogurl'])) {
			if(isset($_POST['blogcategory']) && !in_array("", $_POST['blogcategory']))	{
				if(isset($_GET['getwidgetcode']) && $_GET['getwidgetcode']=='black') { 
					$blackstyle = "class='pickhiglight'";
					$whitestyle = "";
				} else {
					$whitestyle = "class='pickhiglight'";
					$blackstyle = "";
				}
				$burl = rtrim(HTTP_SERVER,'/')."?getwidgetcode=";
				$blogurl = "<span ".$whitestyle." style='float:left;'><a href='".$burl."white' onclick=\"new Ajax.Updater('yourwidget', '".$burl."white');\" title='white background widget'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-white.gif' alt='nominate this blog' /></a></span> ";
				$blogurl .= "<span ".$blackstyle." style='float:left;'><a href='".$burl."black' onclick=\"new Ajax.Updater('yourwidget', '".$burl."black');\" title='black background widget'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-black.gif' alt='nominate this blog' /></a></span><div style='clear:both;'></div>";
				$widgetcode = "<a href='".HTTP_SERVER."nominate?blog=".urlencode($_SESSION['widget-blogurl'])."&category=".$_SESSION['widget-categories']."' title='Nominate Me for the 2007 SA Blog Awards'><img src='".HTTP_SERVER.IMG_DIR."nominate-me-".(($blackstyle!="")?"black":"white").".gif' alt='nominate this blog' /></a>";
				$blogurl = "<div id='get-widget-code'>".$blogurl."<small>Select the badge you like above and then <br />copy and paste this code below into your blog</small><br /><textarea name='copycode' rows='3' cols='30' onclick='this.select();'>".$widgetcode."</textarea></div>";
			}	else $blogurl = "<span class='error'>Sorry, You must select a category.</span>";
		} else $blogurl = "<span class='error'>Sorry, Invalid Blog URL.</span>";
		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $blogurl;
			exit;
		}
	}

	//prepopulate nomination for with nominate me referer
	if(isset($_GET['blog']) && trim($_GET['blog'])!="" && isset($_GET['category'])) {
		$cats = explode(',', $_GET['category']);
		foreach($cats as $c) $urls[$c.'_0'] = urldecode($_GET['blog']);
		$nominateme = 1;
	} else {
		$urls = array();
		$nominateme = 0;
	}
	
	//confirm nominations
	if(isset($_GET['confirmationcode']) && trim($_GET['confirmationcode'])!="") {
		$db->Query("SELECT * FROM user;");
		$users = $db->getResults();
		foreach($users as $u) {
			if(md5(SALT.$u['email'])==$_GET['confirmationcode']) {
				$db->Query("UPDATE user_nomination SET confirmed = '1' WHERE user_id = '".$u['id']."';");
				$db->Query("SELECT nomination_id FROM user_nomination WHERE user_id = '".$u['id']."';");
				$uns = $db->getResults();
				foreach($uns as $un) $db->Query("UPDATE nomination SET nomination_count = (nomination_count+1) WHERE id = '".$un[0]."';");
				$ret = "<span class='success'>Congratulations! You nomination has successfully been confirmed. Thank you.</span>";
			}
		}
		if(!$ret) $ret = "<span class='success'>Sorry, but the confirmation code you entered is incorrect.</span>";
	}

	//submit new nominations
	$flash = "";	
	if(isset($_POST['submit'])) {
		$code = $_POST['validate'];
		$post_email = $_POST['email'];
		//first validate nominations
		$db->Query("SELECT id, count FROM category;");
		while($db->getRow()) {
			$exclude_list = array();
			for($i=0; $i<$db->access['count']; $i++) {
				if(isset($_POST['url_'.$db->access['id'].'_'.$i]) && trim($_POST['url_'.$db->access['id'].'_'.$i])!="") {
					$urls[$db->access['id']."_".$i] = rtrim($_POST['url_'.$db->access['id'].'_'.$i], '/');
					if(valid_url($urls[$db->access['id']."_".$i])) {
						if(!in_array($urls[$db->access['id']."_".$i], $exclude_list)) $exclude_list[] = $urls[$db->access['id']."_".$i];
						else $flash = "<span class='error'>Sorry, Can't have duplicate blog in the same category.</span>";
					} else $flash = "<span class='error'>Sorry, You have enter an invalid blog URL in your nomination.</span>";
				}
			}
		}
		//if no errors with nominations, validate the persons email and security code
		if(!$flash) {
			if(count($urls)>=3 || $_POST['nominateme']==1) {
				if(valid_email_address($email)) {
					if ( strtoupper($_POST['validate']) == strtoupper( trim ( fread ( fopen ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt", "r"), filesize ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt" ) ) ) ) ) {
						$flash = submit_nomination($_POST['email'], $urls, $_POST['nominateme']);
						unlink ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt" );
						$clearform = true;
					} else $flash = "<span class='error'>Sorry, Invalid Authentication Code, Please retype it in and submit again.</span>";
				} else $flash = "<span class='error'>Sorry, but the email address you entered is not valid</span>";
			} else $flash = "<span class='error'>Sorry, you've only submitted ".count($urls)." blog(s). You need to submit a minimum of 3 blogs.</span>";
		}
		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $flash;
			exit;
		}
	} else {
		//regular page load, not submitting anything
		$string = $code = "";
		//Create an unique validation string
		$chars = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
		for ( $i = 0; $i < 5; $i++ ) $string .= $chars{rand(0, (strlen($chars)-1))};
		$id = time();
		$post_email = "";
		fwrite ( fopen ( FILE_SERVER.INCLUDE_DIR."captcha/".$id.".txt", "w" ), $string );
	}
	
	function submit_nomination($email, $urls, $nominateme) {
		//nominate me argument is there to bypass duplicate user nomination overwrite feature for the nominate me widget.
		$db = new CDatabase();
		$db->Connect();
		//check for previously submitted nominations. if so cascade delete those old nominations, if not add the new user to the db and continue
		$db->Query("SELECT * FROM user WHERE email = '".$email."';");
		if($db->getRow()) {
			$user_id = $db->access['id'];
			$db->Query("SELECT nomination_id FROM user_nomination WHERE user_id = '".$user_id."';");
			$uns = $db->getResults();
			foreach($uns as $un) {
				$db->Query("SELECT contestant_id FROM nomination WHERE id = '".$un['nomination_id']."';");
				$db->getRow(); $contestant_id = $db->access['contestant_id'];
				$db->Query("SELECT count(*) FROM nomination WHERE contestant_id = '".$contestant_id."';");
				if($db->access[0]==1 && $nominateme==0) $db->Query("DELETE FROM contestant WHERE id = '".$contestant_id."';");
				$db->Query("SELECT count(*) FROM user_nomination WHERE user_id = '".$user_id."' AND nomination_id = '".$un['nomination_id']."';");
				$db->getRow();
				if($nominateme==0) {
					if($db->access[0]==1) $db->Query("DELETE FROM nomination WHERE id = '".$un['nomination_id']."';");
					else $db->Query("UPDATE nomination SET nomination_count = (nomination_count-1) WHERE id = '".$un['nomination_id']."';");
				}
			}
			if($nominateme==0) $db->Query("DELETE FROM user_nomination WHERE user_id = '".$user_id."';");
		} else {
			//new user nomination, so don't need to delete previous nominations
			$db->Query("INSERT INTO user(`email`) VALUES ('".$email."');");
			$user_id = $db->insertID;
		}
		/*
		 * took this out, because it was interrupting the nomination submissions.
		 * simplepie library is meant to fetch the name of the  nominated blog url, by checking the blog's RSS title
		 * the name of the blog is needed for the voting phase and maybe to make the panel judges job a little nicer by showing them the blog name, rather than an ugly url
		*/
		//include('../'.INCLUDE_DIR.'simplepie.inc');
		//$feed = new SimplePie();
		foreach($urls as $key=>$value) {
			$cat_id = rtrim($key, '_');
			$u = $value;
			//@$feed->feed_url($u);
			//@$feed->init();
			//@$feed->handle_content_type();
			$name = '';//@$feed->get_feed_title();
			
			//check for and add new contestant if necessary
			//should clean up the url here to prevent entering, what is essentially, the same url more than once into the database. (eg. http://www.rafiq.za.net is the same as http://rafiq.za.net)
			$db->Query("SELECT * FROM contestant WHERE url = '".$u."';");
			if($db->getRow()) $blog_id = $db->access['id'];
			else {
				$db->Query("INSERT INTO contestant(`name`, `url`, `contest_id`) VALUES ('".$name."', '".$u."', '1')");
				$blog_id = $db->insertID;
			}
			
			//check for and add nomination if necessary, else just increment nomination count
			$db->Query("SELECT * FROM nomination WHERE contestant_id = '".$blog_id."' AND category_id = '".$cat_id."';");
			if($db->getRow()) $nom_id = $db->access['id'];
			else {
				$db->Query("INSERT INTO nomination(`contestant_id`, `category_id`) VALUES ('".$blog_id."', '".$cat_id."');");
				$nom_id = $db->insertID;
			}
			
			// log the user's nomination to the database
			$db->Query("INSERT INTO user_nomination(`user_id`, `nomination_id`, `confirmed`) VALUES ('".$user_id."', '".$nom_id."', '0');");
		}
		
		return send_conf_email($email);
	}
	
	function send_conf_email($email) {
		$db = new CDatabase();
		$db->Connect();
		$confirm_link = HTTP_SERVER.'?confirmationcode='.md5(SALT.$email);
		$nominations = "";
		$exclude_list = array();
		$db->Query("SELECT DISTINCT category.name, contestant.url FROM user, category, contestant, nomination, user_nomination
									WHERE category.id = nomination.category_id 
									AND contestant.id = nomination.contestant_id
									AND nomination.id = user_nomination.nomination_id
									AND user.id = user_nomination.user_id 
									AND user.email='".$email."' ORDER BY category.id ASC");
		while($db->getRow()) {
			if(!in_array($db->access[0],$exclude_list)) {
				$exclude_list[] = $db->access[0];
				$nominations .= "\n".$db->access[0].": \n"." ".$db->access[1]."\n";
			} else $nominations .= " ".$db->access[1]."\n";
		}
		
		include_once(FILE_SERVER.INCLUDE_DIR."nxs_mimemail.inc.php");
		$mimemail = new nxs_mimemail();
		$subject = "Nomination Confirmation";
		$txt = "Thank you for your blog nominations in the 2007 South African Blog Awards.\n".
					 "\nYour nomination details are as follows:\n".$nominations.
					 "\nIf this is correct please click on the following link or, if the website link bellow doesn't work, please copy and paste it into you browser address bar and press enter.\n".
					 "\nConfirmtion Link: ".$confirm_link.
					 "\n\nPlease be reminded that should you submit another the nomination this one will be replaced.";

		$html = "<html><body><p>Thank you for your blog nominations in the 2007 South African Blog Awards.</p>".
						"<p>Your nomination details are as follows:</p>".nl2br($nominations).
						"<p>If this is correct please click on the following link or, if the website link bellow doesn't work, please copy and paste it into you browser address bar and press enter.</p>".
						"<p>Confirmtion Link: ".$confirm_link.
						"</p><p>Please be reminded that should you submit another the nomination this one will be replaced.</p>";
		$mimemail->new_mail(MASTER_EMAIL, $email, $subject, $text, $html);
		$mimemail->set_from(MASTER_EMAIL, 'SA Blog Awards');
		if($mimemail->send()) return "<span class='success'>Thank you for your nomination. A confirmation email has been sent to you.</span>";
		else return "<span class='error'>Sorry, Unable to send the confirmation email to you.</span>";
	}
	
?>